package cn.edu.wdu.gaojie.reflection.homework2;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class AppCore {
    public static void main(String[] args) throws Exception {
        // TODO
        // 1. 通过反射得到 CoreService 类的实例 c
        // 2. 调用实例 c 的 say 方法并看到输出结果
        // 要求：不要使用 new 关键字

        Class<?> Core = Class.forName("cn.edu.wdu.gaojie.reflection.homework2.CoreService");
        //相当于一个new CoreService();
        Object core = Core.newInstance();

        // getDeclaredFields ：通过类对象获取该类下所有的字段
        Field[] fields = Core.getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            Class<?> type = field.getType();
            if (type.toString().endsWith("CustomerService")) {
                Class<?> Cust = Class.forName("cn.edu.wdu.gaojie.reflection.homework2.CustomerService");
                Object customer = Cust.newInstance();
                field.set(core, customer);
            } else if (type.toString().endsWith("OrderService")) {
                Class<?> Order = Class.forName("cn.edu.wdu.gaojie.reflection.homework2.OrderService");
                Object order = Order.newInstance();
                field.set(core, order);
            } else if (type.toString().endsWith("UserService")) {
                Class<?> User = Class.forName("cn.edu.wdu.gaojie.reflection.homework2.UserService");
                Object user = User.newInstance();
                field.set(core, user);
            }
        }

        Method say = Core.getMethod("say");
        say.invoke(core);

    }

}
